package com.ziq.zcamp.api.service

import android.annotation.SuppressLint
import android.util.Log
import com.blankj.utilcode.util.GsonUtils
import com.gmlive.camp.data.exception.LocalException
import com.ziq.zcamp.api.request.CampBaseRequest
import com.ziq.zcamp.api.respond.CampBaseRespond
import com.ziq.zcamp.api.respond.EncryptionRespond
import com.ziq.zcamp.util.encrypt.AesVr
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resumeWithException

@SuppressLint("CheckResult")
suspend inline fun <reified T : CampBaseRespond?> Observable<T>.request() : T {
    return suspendCancellableCoroutine {
        this.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {response ->
                    response?.let { result ->
                        if(result.isSuccess){
                            it.resumeWith(Result.success(result))
                        } else {
                            it.resumeWithException(NetWorkException(result.dmError, result.errorMsg?:""))
                        }
                    }
                },{throwable->
                    it.resumeWithException(LocalException(-1, throwable.message?:""))
                }
            )
    }
}


inline fun <reified T : CampBaseRespond?> EncryptionRespond.decrypt(encryptionUtils : AesVr, clazz: Class<T>) : T {
    val result = clazz.newInstance()
    try {
        val field = clazz.getDeclaredField("data")
        field.isAccessible = true
        val data = if (this.data?.isNotEmpty() == true){
            GsonUtils.fromJson(encryptionUtils.decode(this.data),field.type)
        }else{
            null
        }
        result?.dmError = this.dmError
        result?.errorMsg = this.errorMsg
        field.set(result,data)
        result
    }catch (e : Exception){
        e.printStackTrace()
    }
    return result
}